﻿var selMap = function () { 
    var map,
        marker,
        btn = true,
        inf = {},
        locationInfo,
        toolBar,
        placeSearch,
        geocoder,
        oLocation = true,
        geolocation,
        oLocation_firstHtml = true,
        timer = null,
        p, item, points = [];
    var _this = {
        initEvent: function () {
            App.loading(-1);
            var point = App.getParams("site") || "";
            var point_arry =point.split(',');
            var self = this;
            //初始化地图对象，加载地图
            map = new AMap.Map('mapContainer', {
                resizeEnable: true,
                //二维地图显示视口
                //设定地图中心点
                //设置地图显示的缩放级别
                view: new AMap.View2D({
                    zoom: 13
                })
            });

            //map.setCity("深圳");
            map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, //是否使用高精度定位，默认:true
                    timeout: 10000, //超过10秒后停止定位，默认：无穷大
                    maximumAge: 0, //定位结果缓存0毫秒，默认：0
                    convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                    showButton: false, //显示定位按钮，默认：true
                    // buttonDom: $('#location_section1 .mapButton .icon.reset').get(0),
                    buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
                    buttonOffset: new AMap.Pixel(10, 10), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 10)

                    showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                    showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                    panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                    zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                });
                map.addControl(geolocation);
                AMap.event.addListener(geolocation, 'complete', onComplete); //返回定位信息
                AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息

                geolocation.getCurrentPosition(onComplete, onError);

            });

            function geocoder_callBack(data) {
                //if (btn) {
                //btn = !btn; 
                if (typeof data != 'object' || !data.regeocode) {
                    return false;
                }
                var html = '',
                    oName = '',
                    olng = '',
                    oLat = '';

                if (data.regeocode.addressComponent.building) {
                    oName = data.regeocode.addressComponent.building;
                } else if (data.regeocode.addressComponent.neighborhood) {
                    oName = data.regeocode.addressComponent.neighborhood;
                } else if (data.regeocode.roads != null && data.regeocode.roads.length > 0) {
                    oName = data.regeocode.roads[0].name;
                }

                if (data.regeocode.addressComponent.businessAreas != null && data.regeocode.addressComponent.businessAreas.length > 0) {
                    olng = data.regeocode.addressComponent.businessAreas[0].location.lng;
                    oLat = data.regeocode.addressComponent.businessAreas[0].location.lat;
                } else if (data.regeocode.roads != null && data.regeocode.roads.length > 0) {
                    olng = data.regeocode.roads[0].location.lng;
                    oLat = data.regeocode.roads[0].location.lat;
                }

                if (oLocation_firstHtml || oLocation) {
                    $('#location_section1 .keyword').attr({
                        'data-lng': olng,
                        'data-lat': oLat,
                        'data-location': data.regeocode.formattedAddress,
                        'data-name': oName
                        /*,  'data-citycode' : data.regeocode.addressComponent.citycode*/
                    }).css('color', '#b4b4b4').text(App.getParams("location") == 'off_site' ? '目的地查询' : '出发地查询');
                }

                if (oLocation) {

                    /*html = '<li  class="active" data-lng="' + olng + '" data-lat="' + oLat + '" data-location = "' + oName + '" data-citycode="' + data.regeocode.addressComponent.citycode + '"><div class="left"><div class="station">' + $('#location_section1 .keyword').attr('data-name') + '</div><div class="road">' + data.regeocode.formattedAddress + '</div></div><div class="right"><button class="ok">确定</button></div></li>';*/
                    html = '<li  class="active hairlines-bottom" data-lng="' + olng + '" data-lat="' + oLat + '" data-location = "' + oName + '" data-citycode="' + data.regeocode.addressComponent.citycode + '"><div class="left"><div class="station">[我的位置]' + $('#location_section1 .keyword').attr('data-name') + '</div><div class="road">' + data.regeocode.formattedAddress + '</div></div><div class="right"><button class="ok">确定</button></div></li>';
                    oLocation = false;
                } else {
                    html = '<li  class="active hairlines-bottom" data-lng="' + $('#location_section1 .keyword').attr('data-lng') + '" data-lat="' + $('#location_section1 .keyword').attr('data-lat') + '" data-location = "' + $('#location_section1 .keyword').attr('data-name') + '" data-citycode="' + data.regeocode.addressComponent.citycode + '"><div class="left"><div class="station">' + $('#location_section1 .keyword').attr('data-name') + '</div><div class="road">' + $('#location_section1 .keyword').attr('data-location') + '</div></div><div class="right"><button class="ok">确定</button></div></li>';
                }


                data.regeocode.pois.forEach(function (item, i) {

                    if (item.name == $('#location_section1 .keyword').attr('data-name')) {
                        return false;
                    }
                    html += '<li class="hairlines-bottom" data-lng="' + item.location.lng + '" data-lat="' + item.location.lat + '" data-location="' + item.name + '" data-citycode ="' + data.regeocode.addressComponent.citycode + '"><div class="left"><div class="station">' + item.name + '</div>';

                    html += '<div class="road">' + item.address + '</div></div><div class="right"><button class="ok">确定</button></div></li>';
                });
                $('#location_section1 .location_con ul').html(html);
                App.loading(true);
                //}
            }
            //拖动地图自动刷新 附近位置信息
            AMap.event.addListener(map, 'dragging', function (e) {
                oLocation_firstHtml = true;
                var p = map.getCenter();
                marker && marker.setPosition(p); 
                geocoder && geocoder.getAddress(p, geocoder_callBack);
                //map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
            });
            //定位
            $("#location_section .ddbUi-lineMap .icon.reset").on('tap', function () {
                geolocation.getCurrentPosition(onComplete, onError);
                // toolBar.doLocation();
            });
            //获取当前位置信息
            function getCurrentPosition() {
                geolocation.getCurrentPosition();
            }
            //监控当前位置并获取当前位置信息
            function watchPosition() {
                geolocation.watchPosition();
            }
            //解析定位结果

            function onComplete(data, position) {
                var p;
                if (position) {
                    p= position.position;
                } else {
                    p = {
                        lng: data.position.getLng(),
                        lat: data.position.getLat()
                    };
                }
                //更新gps信息.
                //App.pgps("user_data_gps", { data: data, position: p });
                //gData.userPosition = $.fn.extend({},data);
                //添加用户当前位置到图层
                var lng = p.lng;
                var lat = p.lat;
                if(point != ""){
                    lng = point_arry[0];
                    lat = point_arry[1];
                }
                if (!marker) {
                    marker = new AMap.Marker({
                        icon: "res/img/select_pos.png",
                        position: new AMap.LngLat(lng, lat)
                    });
                }
                var p = new AMap.LngLat(lng, lat);
                map.setCenter(p);
                map.setZoom(14);
                marker.setMap(map); //在地图上添加点

                var lnglatXY = new AMap.LngLat(p.lng, p.lat);
                map.plugin(["AMap.Geocoder"], function () {
                    geocoder = new AMap.Geocoder({
                        radius: 1000, //以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
                        extensions: "all" //返回地址描述以及附近兴趣点和道路信息，默认"base"
                    });
                    //返回地理编码结果
                    AMap.event.addListener(geocoder, "complete", geocoder_callBack);
                    //逆地理编码


                    geocoder.getAddress(lnglatXY);

                });

                //setDriverMaker();

            };
            //解析定位错误信息
            function onError(data) {
                var str = '<p>定位失败</p>';
                str += '<p>错误信息：';
                switch (data.info) {
                    case 'PERMISSION_DENIED':
                        str += '浏览器阻止了定位操作';
                        break;
                    case 'POSITION_UNAVAILBLE':
                        str += '无法获得当前位置';
                        break;
                    case 'TIMEOUT':
                        str += '定位超时';
                        break;
                    default:
                        str += '未知错误';
                        break;
                }
                str += '</p>'; 
            };
            //浏览器方式定位    解析定位结果
            function navComplete(data) {
                var p = {
                    lat: data.coords.latitude,
                    lng: data.coords.longitude
                }

                //todo 保存用户位置信息
                /*    var p =  {lng:data.position.getLng(),lat: data.position.getLat()};
              gData.userPosition = $.fn.extend({},data);*/

                //添加用户当前位置到图层
                if (!marker) {
                    marker = new AMap.Marker({
                        /*icon: "http://webapi.amap.com/images/marker_sprite.png",*/
                        position: new AMap.LngLat(p.lng, p.lat)
                    });

                }
                var p = new AMap.LngLat(p.lng, p.lat);
                map.setCenter(p);
                map.setZoom(14);
                marker.setMap(map); //在地图上添加点

            };
            //浏览器方式定位    解析定位结果
            function navError(data) { 
            };
            $('#location_section2 input[type="text"]').on('input', function () {
                self.search(this.value);
            });
            $('#location_section2 .location_con ul').on('click', '.data', function () {
                oLocation_firstHtml = false;
                oLocation = false;
                var LdbSearch = App.store("LdbSearch") || []; 
                var LdbSearchBol = true;
                for (var j = 0; j < LdbSearch.length; j++) {
                    if (LdbSearch[j].split('/')[0] == $(this).find('.station').text()) {
                        LdbSearchBol = false;
                    }
                }
                if (LdbSearchBol) {
                    LdbSearch.unshift($(this).find('.station').text() + "/" + $(this).find('.road').text() + "/" + $(this).attr('data-lng') + "/" + $(this).attr('data-lat'));
                }
                App.store("LdbSearch", LdbSearch);

                $('#location_section1').css('display', 'block');
                $('#location_section2').css('display', 'none');
                inf.lng = $(this).attr('data-lng');
                inf.lat = $(this).attr('data-lat');
                var p = new AMap.LngLat(inf.lng, inf.lat);

                map.setZoom(14);
                map.setCenter(p);
                marker && marker.setPosition(p);
                $('#location_section1 .keyword').css('color', '#000');
                $('#location_section1 .keyword').text($(this).find('.station').text());
                $('#location_section1 .keyword').attr({
                    'data-lng': inf.lng,
                    'data-lat': inf.lat,
                    'data-name': $(this).find('.station').text(),
                    'data-location': $(this).find('.road').text()
                });

                btn = true;
                //oLocation = false;

                geocoder && geocoder.getAddress(p); /*3333333 */
                //浏览器历史记录(搜索后选中地址)
                var historyurl = location.href.replace('&page=clicksearch', '');
                history.pushState(null, null, historyurl + '&page=clicksearched');

                return false;
            });
            $('#location_section1 .location_con ul').on('click', 'li', function () {
                $('#location_section1 .location_con ul li').removeClass('active');
                $('#location_section1 .location_con ul li').addClass('hairlines-bottom');
                $(this).addClass('active');
                $(this).prev().removeClass('hairlines-bottom');
                inf.lng = $(this).attr('data-lng');
                inf.lat = $(this).attr('data-lat');
                inf.location = $(this).attr('data-location');
                var p = new AMap.LngLat(inf.lng, inf.lat);
                map.setZoom(14);
                map.setCenter(p);
                marker.setPosition(p);
                /*$('.keyword').val($(this).find('.station').text());*/
                $('#location_section1 .keyword').attr({
                    'data-lng': inf.lng,
                    'data-lat': inf.lat,
                    'data-name': inf.location
                });

                return false;
            });
            $('#myMapS').on('click', function () {
                $('#location_section1').css('display', 'none');
                $('#location_section2').css('display', 'block');
                $('#location_section2 .keyword').focus().trigger('click');

               
                var LdbSearch = App.store("LdbSearch") || [];
                // localstorage旧缓存兼容性修改
                if (typeof LdbSearch === "string") {
                    LdbSearch = LdbSearch.split(',');
                    App.store("LdbSearch", LdbSearch);
                }

                var html = '';
                $.each(LdbSearch, function (i, item) {
                    var addrs = item.split('/');
                    var len = addrs.length;
                    var lng = addrs[len - 2];
                    var lat = addrs[len - 1];
                    var addr_name = addrs[0];
                    var addr_des = item.replace(addr_name + '/', '').replace('/' + lng + '/' + lat, '');
                    html += '<li class="data hairlines-bottom" data-lng=' + lng + ' data-lat=' + lat + '><div class="station">' + addr_name + '</div><div class="road">' + addr_des + '</div></li>';
                });
                $('#location_section2 .location_con ul').html(html);

                //浏览器历史记录(点击查询)
                //var historyurl = location.href.replace('&page=clicksearched', '');
                //history.pushState(null, null, historyurl + '&page=clicksearch');
            });
            $('#close').on('click', function () {
                $('#location_section1').css('display', 'block');
                $('#location_section2').css('display', 'none');
                history.go(-2);
            });
            $('#del').on('click', function () {
                $('#location_section2 .keyword').val('');
                var LdbSearch = window.localStorage.getItem("LdbSearch");
                if (LdbSearch === null) {
                    LdbSearch = [];
                }
                var html = '';
                $.each(LdbSearch, function (i, item) {
                    var addrs = item.split('/');
                    var len = addrs.length;
                    var lng = addrs[len - 2];
                    var lat = addrs[len - 1];
                    var addr_name = addrs[0];
                    var addr_des = item.replace(addr_name + '/', '').replace('/' + lng + '/' + lat, '');
                    html += '<li class="data hairlines-bottom" data-lng=' + lng + ' data-lat=' + lat + '><div class="station">' + addr_name + '</div><div class="road">' + addr_des + '</div></li>';

                });
                $('#location_section2 .location_con ul').html(html);
            });
            $(".newBack").on("click", function () {
                history.back(-1);
            });
            //确定按钮
            $('#location_section1  ul').on('click', 'button.ok', function () {
                var d =$(this).parent();
                var roadstr =d.siblings().find(".road").text();
                var v = $('#location_section1 nav .keyword');
                var _order = {};
                var lng = v.attr('data-lng');
                var lat = v.attr('data-lat');
                _order.startPoint = lng + "," + lat;
                _order.startAddress = roadstr;
                window.parent.App.selectMap.notify({ "result": _order });
                var lay =window.parent.layer;
                if (typeof (lay) !== "undefined") {
                    lay.closeAll();
                }
                //window.location.href = 'commuter.html?load=Y'
                return false;
            });
        },
        search: function (keyword) {
            // 设置查询类别
            var searchType = App.store('app/get_common_data');
           
            searchType = searchType ? searchType.data.poi_search_types : "商务住宅|公交车站|地铁站|学校";

            AMap.service(["AMap.PlaceSearch"], function () {
                placeSearch = new AMap.PlaceSearch({
                    //type: searchType, // 设置查询类别,多个类别用"|"分割
                    //city: App.store('ddbCity') ? App.store('ddbCity').split('/')[0] : '深圳',
                    radius: 1000,
                    extensions: "all"
                });
                placeSearch.search(keyword, function (status, result) {
                    if (status == 'complete') {
                        var html = '';

                        //result.poiList.pois.forEach(function (item) {
                        //    html += '<li class="data hairlines-bottom" data-lng="' + item.location.lng + '" data-lat="' + item.location.lat + '"><div class="station">';
                        //    html += item.name.replace(new RegExp(keyword, 'g'), '<span class="light">' + keyword + '</span>');
                        //    html += '</div><div class="road">' + item.address + '</div></li>';
                        //});
                        $.each(result.poiList.pois, function (i, item) {
                            html += '<li class="data hairlines-bottom" data-lng="' + item.location.lng + '" data-lat="' + item.location.lat + '"><div class="station">';
                            html += item.name.replace(new RegExp(keyword, 'g'), '<span class="light">' + keyword + '</span>');
                            html += '</div><div class="road">' + item.address + '</div></li>';
                        })
                        $('#location_section2 .location_con ul').html(html);
                    } else if (status == 'no_data') {
                        $('#location_section2 .location_con ul').html('<li><div class="empty_box">没有找到相关地址</div></li>');
                    }
                });
            });
        },
        init: function () {
            _this.initEvent();
        }
    }
    return _this;
}();
$(function () {
    selMap.init();
})